/**
 * 
 */
package com.android.dwt.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.provider.SearchRecentSuggestions;
import android.util.Log;
import android.widget.Toast;

import com.android.dwt.R;
import com.android.dwt.R.string;
import com.android.dwt.R.xml;
import com.android.dwt.data.GTDApp;
import com.android.dwt.data.MySuggestionsProvider;
import com.android.dwt.service.DWTService;
import com.android.dwt.service.DWTService.MyBinder;
import com.android.dwt.util.C;

/**
 * @author xiang
 *
 */
public class SettingAct extends PreferenceActivity
		implements OnPreferenceChangeListener, OnPreferenceClickListener, OnSharedPreferenceChangeListener,
					DialogInterface.OnClickListener, ServiceConnection {
	
	private final String TAG = "SettingAct";
	private final int BACKUP = 0;
	private final int RESTORE = 1;
	
	private GTDApp mGa;
	private String mStrRingtone;
	private String mStrVibration;
	private String mStrClearHistory;
	
	private Uri mRingtoneUri = null;		// default silent
	private Boolean mVibration = true;
	private int mGpsRemind;
	
	private RingtonePreference mRingtone;
	private Preference mClearHistory;
	private Preference mBackup;
	private Preference mRestore;
	private CheckBoxPreference mPosRemind;
	

	/*public Boolean isVibration() {
		if (mVibration)
			return true;
		else
			return false;
	}
	
	public Uri getRingtone() {
		return mRingtoneUri;
	}*/
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		mGa = (GTDApp) getApplication();
		
		addPreferencesFromResource(R.xml.preferences);
		
		getKeyString();
		
		initPreference();
		
		registerListener();
		
	}
	
	private void getKeyString() {
		
		mStrRingtone = getString(R.string.key_ringtone);
		mStrVibration = getString(R.string.key_vibrate);
		mStrClearHistory = getString(R.string.key_clear);
	}
	
	private void initPreference() {
		
		mRingtone =  (RingtonePreference) findPreference(mStrRingtone);
		mClearHistory = (Preference) findPreference(mStrClearHistory);
		mBackup = (Preference) findPreference("backup");
		mRestore = (Preference) findPreference("restore");
		mPosRemind = (CheckBoxPreference) findPreference("pos_remind");
	}
	
	private void registerListener() {
		
		mRingtone.setOnPreferenceChangeListener(this);
		mRingtone.setOnPreferenceClickListener(this);
		mClearHistory.setOnPreferenceClickListener(this);
		mBackup.setOnPreferenceClickListener(this);
		mRestore.setOnPreferenceClickListener(this);
//		mPosRemind.setOnPreferenceChangeListener(this);
//		mPosRemind.setOnPreferenceClickListener(this);
		
		PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
	}

	@Override
	public boolean onPreferenceClick(Preference preference) {

		String key = preference.getKey();
		
		if (key.equals(mStrClearHistory)) {	// clear recent suggestion
			
			clearSearchHistory();
			
			Toast.makeText(this, "搜索历史已清空", Toast.LENGTH_LONG).show();
			
		} else if (key.equals("backup")) {
			
			String state = Environment.getExternalStorageState();
			if (Environment.MEDIA_MOUNTED.equals(state) == false) {		// sdcare not available
				Toast.makeText(SettingAct.this, getString(R.string.msg_sdcard), Toast.LENGTH_LONG)
					.show();
				
				return false;
			}
			
			backupData();
			
			// backup successfully
			Toast.makeText(SettingAct.this, getString(R.string.msg_bak_success), Toast.LENGTH_LONG)
				.show();

		} else if (key.equals("restore")) {
			
			AlertDialog.Builder builder = new AlertDialog.Builder(SettingAct.this);
			builder.setTitle("恢复数据将清空手机上现有的数据，是否继续？");
			builder.setPositiveButton("恢复", this);
			builder.setNegativeButton("不恢复", this);
			builder.show();
			
		} else {
			
			;
		}
			
		
		return true;
	}
	
	private void clearSearchHistory() {
		
		SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
				MySuggestionsProvider.AUTHORITY,
				MySuggestionsProvider.MODE);
		suggestions.clearHistory();
	}

	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue) {
		
		String key = preference.getKey();
		
		if (key.equals("ringtone")) {
//			mRingtone.setSummary((String) newValue);
			Toast.makeText(SettingAct.this, "ringtone", Toast.LENGTH_LONG).show();
			
		} else {
			;
		}
		
		return false;
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		
		// TODO Auto-generated method stub
		String name = "";
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		
		if (key.equals(mStrRingtone)) {
			
			String strRingtonePreference = prefs.getString(mStrRingtone, "");
			
			if (strRingtonePreference.length() == 0) {	// silent
				
				name = getString(R.string.silent);
				
			} else {
				
				mRingtoneUri = Uri.parse(strRingtonePreference);
				Ringtone ringtone = RingtoneManager.getRingtone(this, mRingtoneUri);
				
				if (ringtone != null)
					name = ringtone.getTitle(this);
			}
			
			mRingtone.setSummary(name);
			
		} else if (key.equals(mStrVibration)) {
			
			mVibration = prefs.getBoolean(mStrVibration, true);
			
		} else if (key.equals("pos_remind")) {
			
			Log.e(TAG, "location remind is clicked!");
			
			Intent i = new Intent(SettingAct.this, DWTService.class);
			i.putExtra("MoreAct", "MoreAct");
			
			boolean checked = prefs.getBoolean("pos_remind", true);
			if (checked) {			// open location alert
				
				Log.e(TAG, "location remind is opened!");
				
				mGa.mPosRemind = true;
				
				mGpsRemind = C.GPS.GPS_ALERT;
				
			} else {				// close location alert
				
				Log.e(TAG, "location remind is closed!");
				
				mGpsRemind = C.GPS.GPS_UNALERT;
				
				mGa.mPosRemind = false;
			}
			
			boolean flag = getApplicationContext().bindService(i, this, BIND_AUTO_CREATE);
			if (flag) {
				
				Log.e(TAG, "bindService returns ture");
				
			} else {
				
				Log.e(TAG, "bindService returns false");
			}
			
		} 
		
		return;
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		
		if (which == AlertDialog.BUTTON_POSITIVE) {
			
			String state = Environment.getExternalStorageState();
			if (Environment.MEDIA_MOUNTED.equals(state) == false) { // sdcard not  available
				Toast.makeText(SettingAct.this,
						getString(R.string.msg_sdcard), Toast.LENGTH_LONG)
						.show();
			}
	
			restoreData();
			((GTDApp) getApplication()).onCreate();		// refresh data
			
			// restore successfully
			Toast.makeText(SettingAct.this, getString(R.string.msg_restore_success),
					Toast.LENGTH_LONG).show();
			
		} else if (which == AlertDialog.BUTTON_NEGATIVE) {
			dialog.dismiss();
		}
		
	}
	
	private void backupData() {
		String curPath, bakPath;
		
		File sdcard = Environment.getExternalStorageDirectory();		// return "/sdcard"
		File data = Environment.getDataDirectory();		/// get internal data directory, return "/data"
		
		if (sdcard.canWrite()) {
			// backup sqlite database
			curPath = "/data/com.android.dwt/databases/dwt.db";
			bakPath = "/DWT/dwt.db";
			transferData(data, sdcard, curPath, bakPath, BACKUP);
			
			// backup contexts
			curPath = "/data/com.android.dwt/shared_prefs/ctts.xml";
			bakPath = "/DWT/prefs/ctts.xml";
			transferData(data, sdcard, curPath, bakPath, BACKUP);
			
			// backup lists
			curPath = "/data/com.android.dwt/shared_prefs/lists.xml";
			bakPath = "/DWT/prefs/lists.xml";
			transferData(data, sdcard, curPath, bakPath, BACKUP);

			// backup positions
			curPath = "/data/com.android.dwt/shared_prefs/pos.xml";
			bakPath = "/DWT/prefs/pos.xml";
			transferData(data, sdcard, curPath, bakPath, BACKUP);
			
			// backup projects
			curPath = "/data/com.android.dwt/shared_prefs/prjs.xml";
			bakPath = "/DWT/prefs/prjs.xml";
			transferData(data, sdcard, curPath, bakPath, BACKUP);
			
			// backup sort
			curPath = "/data/com.android.dwt/shared_prefs/sort.xml";
			bakPath = "/DWT/prefs/sort.xml";
			transferData(data, sdcard, curPath, bakPath, BACKUP);
			
			// backup sort
			curPath = "/data/com.android.dwt/shared_prefs/tags.xml";
			bakPath = "/DWT/prefs/tags.xml";
			transferData(data, sdcard, curPath, bakPath, BACKUP);
		}
	}
	
	private void restoreData() {
		String curPath, restorePath;
		
		File sdcard = Environment.getExternalStorageDirectory(); 	// return  "/sdcard"
		File data = Environment.getDataDirectory(); 				// get internal data directory, return "/data"

		if (sdcard.canRead()) {
			
			curPath = "/DWT/dwt.db";
			restorePath = "/data/com.android.dwt/databases/dwt.db";
			transferData(sdcard, data, curPath, restorePath, RESTORE);
			
			curPath = "/DWT/prefs/ctts.xml";
			restorePath = "/data/com.android.dwt/shared_prefs/ctts.xml";
			transferData(sdcard, data, curPath, restorePath, RESTORE);
			
			curPath = "/DWT/prefs/lists.xml";
			restorePath = "/data/com.android.dwt/shared_prefs/lists.xml";
			transferData(sdcard, data, curPath, restorePath, RESTORE);
			
			curPath = "/DWT/prefs/pos.xml";
			restorePath = "/data/com.android.dwt/shared_prefs/pos.xml";
			transferData(sdcard, data, curPath, restorePath, RESTORE);
			
			curPath = "/DWT/prefs/prjs.xml";
			restorePath = "/data/com.android.dwt/shared_prefs/prjs.xml";
			transferData(sdcard, data, curPath, restorePath, RESTORE);
			
			curPath = "/DWT/prefs/sort.xml";
			restorePath = "/data/com.android.dwt/shared_prefs/sort.xml";
			transferData(sdcard, data, curPath, restorePath, RESTORE);
			
			curPath = "/DWT/prefs/tags.xml";
			restorePath = "/data/com.android.dwt/shared_prefs/tags.xml";
			transferData(sdcard, data, curPath, restorePath, RESTORE);
			
		}
		
		return;
	}
	
	private void transferData(File from, File to, String fromPath, String toPath, int flag) {
		File fromData, toData;
		
		try {
			fromData = new File(from, fromPath);
			if (flag==RESTORE && !fromData.exists()) {		// no previous backup data, nothing happened
				/*Toast.makeText(MoreAct.this,
						getString(R.string.msg_error_restore),
						Toast.LENGTH_LONG).show();*/
				
				return;
			}
			
			toData = new File(to, toPath);
			if (!toData.getParentFile().exists()) {
				toData.getParentFile().mkdirs();
			}
			if (!toData.exists())
				toData.createNewFile();
			
			FileInputStream src = new FileInputStream(fromData);
			FileOutputStream dest = new FileOutputStream(toData);
			
			byte[] buf = new byte[1024];
			int length;
			while ((length=src.read(buf)) > 0) {
				dest.write(buf, 0, length);
			}
			
			dest.flush();
			dest.close();
			src.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
		
		Log.e(TAG, "location remind service connection is successful!");
		
		MyBinder binder = (MyBinder) service;
		DWTService svc = binder.getService();
//		Handler handler = svc.getHander();
		
		svc.checkGPS(SettingAct.this);
		
//		handler.sendEmptyMessage(mGpsRemind);
		
		getApplicationContext().unbindService(this);
	}

	@Override
	public void onServiceDisconnected(ComponentName name) {
		// TODO Auto-generated method stub
		
	}
	
}
